package com.pc.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pc.entity.Money;
import com.pc.mapper.MoneyMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MoneyService {
    @Resource
    private MoneyMapper moneyMapper;

    //得到账户余额
    public Integer getUserMoney(String username){
        QueryWrapper<Money> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Money money = moneyMapper.selectOne(wrapper);
        return money.getMoney();
    }
    //充值
    public boolean addMoney(String username,Integer addmoney){
        QueryWrapper<Money> wq = new QueryWrapper<>();
        wq.eq("username",username);
        Money nowmoney = moneyMapper.selectOne(wq);
        Money money = new Money();
        int dq=nowmoney.getMoney();
        money.setMoney(dq+addmoney);
        int update = moneyMapper.update(money, wq);
        return update!=0;
    }
    //付款
    public boolean subMoney(String userName,Integer subMoney){
        QueryWrapper<Money> wrapper = new QueryWrapper<>();
        wrapper.eq("username",userName);

        Money choicemoney = moneyMapper.selectOne(wrapper);
        Money money = new Money();
        Integer coin = choicemoney.getMoney();
        if (coin-subMoney <0)
            return false;
        else {
            money.setUsername(userName);
            money.setMoney(coin-subMoney);
            int update = moneyMapper.update(money, wrapper);
            return update!=0;
        }
    }

    //添加用户
    public boolean addUserMoney(String username){
        Money money = new Money();
        money.setMoney(3000);
        money.setUsername(username);
        int insert = moneyMapper.insert(money);
        return insert!=0;
    }

    //得到总共的营业额
    public int getAllMoney(){
        QueryWrapper<Money> wrapper = new QueryWrapper<>();
        int summoney=0;

        List<Money> list = moneyMapper.selectList(wrapper);
        for (Money money : list) {
            summoney += money.getMoney();
        }

        return summoney;
    }
}
